package com.kiliter.interceptor;


import com.kiliter.annotations.ApiIdempotence;
import com.kiliter.service.ApiTokenService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @ClassName zhangjl
 * @date 2021/6/7 10:56
 * @Version 1.0
 */
@Component
@RequiredArgsConstructor
public class ApiInterceptor extends HandlerInterceptorAdapter {


    private final ApiTokenService apiTokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        HandlerMethod method = (HandlerMethod) handler;
        Method method1 = method.getMethod();
        ApiIdempotence annotation = method1.getAnnotation(ApiIdempotence.class);
        if(annotation!=null){
            apiTokenService.checkToken(request);
        }
        return true;
    }

}
